<?php
// +---------------------------------------------------------------
// | Tommy Framework
// +---------------------------------------------------------------
// | Copyright (c) 2009 http://www.tommycode.com All rights reserved.
// +---------------------------------------------------------------
// | Author: streen003 <streen003gmail.com>
// +---------------------------------------------------------------

if(!defined('IN_TOMMY')){

	exit;
}

class Db extends Base{
	
	//定义变量
	protected static $instance; //用于构建类的singleton模式参数
	public $db_link;
	protected $transtimes;
	
	//构造函数，用于初始化类的应用环境
	public function __construct($params) {

		$this->db_link = new mysqli($params['host'],$params['username'],$params['password'],$params['dbname']);

		if (mysqli_connect_errno()) {
			
			if(TOMMY_DEBUG == true){

				trigger_error('Mysql Server connect fail <br>Error Message: '.mysqli_connect_error().'<br>Error Code: '.mysqli_connect_errno(),E_USER_ERROR);
			}
			else{

				Log::write('Mysql Server connect fail. Error Code:'.mysqli_connect_errno().' Error Message:'.mysqli_connect_error(), 'Warning');

				Controller::show_msg('Mysql Server connect fail', -1);
			}
		}
		else {

			$this->db_link->query("SET NAMES {$params['charset']}");

			$sql_version = $this->get_server_info();

			if (version_compare($sql_version,'5.0.2','>=')) {

				$this->db_link->query("SET SESSION SQL_MODE=''");
			}
		}

		return true;
	}

	//执行SQL语句函数
	public function query($sql) {

		$result = $this->db_link->query($sql);

		if ($result==false) {

			if(TOMMY_DEBUG==true){

				trigger_error('SQL execute failed: '.$sql.'<br>Error Message: '.$this->error().'<br>Error Code: '.$this->errno().'<br>Error SQL: '.$sql,E_USER_ERROR);
			}
			else{

				Log::write('SQL execute failed. SQL code:'.$sql.' Error Code:'.$this->errno().'Error Message: '.$this->error());

				Controller::show_msg('Database program run error', -1);
			}
		}

		return $result;
	}
	
	//获取MYSQL SERVER信息
	private  function get_server_info() {

		if (!$this->db_link) {

			return false;
		}

		$sql_version = $this->db_link->server_version;

		return $sql_version;
	}
	
	//获取MYSQL 错误描述信息
	public function error() {

		return $this->db_link->error;
	}

	//获取MYSQL 错误信息代码
	public function errno() {

		return $this->db_link->errno;
	}

	//通过一个SQL语句获取一行信息（字段型）
	public function fetch_row($sql) {

		$result = $this->query($sql);

		if($result) {

			$rows = $result->fetch_assoc();

			$result->free();
		}

		return $rows;
	}

	//通过一个SQL语句获取全部信息（字段型）
	public function get_array($sql) {

		$result = $this->query($sql);

		$myrow=array();

		if($result) {

			while ($row=$result->fetch_assoc()) {

				$myrow[]=$row;
			}

			$result->free();
		}

		return $myrow;
	}
	
	//获取执行结果的总行数
	public function num_rows($sql) {
		
		$result = $this->query($sql);

		return $result->num_rows;
	}
	
	//获取insert_id
	public function insert_id() {
		
		return $this->db_link->insert_id;
	}

	//开启事务处理
	public function startTrans() {
		
		if($this->transtimes == false) {
			
			$this->db_link->autocommit(false);
		}
		
		$this->transtimes = true;
		
		return true;
	}
	
	//提交事务处理
	public function commit() {
		
		if($this->transtimes == true) {
			
			$result = $this->db_link->commit();
			
			if($result) {
				
				$this->db_link->autocommit(true);
			
				$this->transtimes = false;
			}
			else {
				
				if(TOMMY_DEBUG == true){

					trigger_error('SQL Commit failed <br>Error Message: '.$this->error().'<br>Error Code: '.$this->errno(),E_USER_ERROR);
				}
				else{

					Log::write('SQL Commit failed. Error Code:'.$this->errno().' Error Message: '.$this->error());

					Controller::show_msg('Database program run error', -1);
				}
			}
		}
		
		return true;
	}
	
	//事务回滚
	public function rollback() {
		
		if($this->transtimes == true) {
			
			$result = $this->db_link->rollback();
			
			if($result) {
				
				$this->db_link->autocommit(true);
				
				$this->transtimes = false;
			}
			else {

				if(TOMMY_DEBUG == true){

					trigger_error('SQL RollBack failed <br>Error Message: '.$this->error().'<br>Error Code: '.$this->errno(),E_USER_ERROR);
				}
				else{

					Log::write('SQL RollBack failed. Error Code: '.$this->errno().' Error Message: '.$this->error());

					Controller::show_msg('Database program run error', -1);
				}
				
			}
		}
		
		return true;
	}
	
	//关闭MYSQL SERVER
	public function close($db_link) {

		if ($db_link==false) {

			return false;
		}

		return $db_link->close();
	}

	//析构函数，用于类程序运行后，打扫战场的作用
	public function __destruct() {

		if ($this->db_link) {

			$this->close($this->db_link);
		}
	}
	
	//用于本类的静态调用,子类需要重载才能正常使用.
    public static function getInstance($params){
		
		if (self::$instance == null) {
		
			self::$instance = new Db($params);
		}
		
		return self::$instance;
	}
}
?>